<!-- 账号列表 -->
<template>
  <div class="flexbox">
    <h2 style="color: #595959">{{ $t("messages.AccountList") }}</h2>
    <div class="btn-group">
      <el-button
        style="
          color: #fff;
          width: 60px;
          height: 30px;
          background-color: #409eff;
        "
        type="text"
        size="small"
        @click="handleIn()"
      >
        导入
      </el-button>
      <el-button
        style="
          color: #fff;
          width: 60px;
          height: 30px;
          background-color: rgb(104, 215, 76);
        "
        type="text"
        size="small"
        @click="exportToExcel()"
      >
        导出
      </el-button>
      <!-- 导入 Excel 文件输入 -->
      <input
        type="file"
        style="display: none"
        ref="excelFileInput"
        @change="handleExcelFileChange"
      />
    </div>
  </div>
  <div>
    <!-- 表格 -->
    <el-table
      ref="tableRef"
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="account" label="账号"></el-table-column>
      <el-table-column prop="userGroup" label="用户组"></el-table-column>
      <el-table-column prop="ctime" label="创建时间"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            style="
              background-color: #409eff;
              color: #fff;
              width: 60px;
              height: 30px;
            "
            type="text"
            size="small"
            @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button
            style="
              border: 1px solid #e8e8e8;
              background-color: #e55443;
              color: #fff;
              width: 60px;
              height: 30px;
            "
            type="text"
            size="small"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- .分页器 -->
    <el-pagination
      style="margin-top: 10px"
      background
      layout="total, sizes ,prev, pager, next"
      :total="total"
      :page-size="pageSize"
      :current-page="currentPage"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    >
      >
    </el-pagination>

    <!-- .模态框 -->
    <el-dialog
      title="编辑账号"
      center
      lock-scroll
      draggable
      v-model="dialogVisible"
      width="50%"
      @close="dialogVisible = false"
    >
      <el-form :model="dialogForm">
        <el-form-item style="margin-left: 30px" label="账号">
          <el-input v-model="dialogForm.account" style="width: 90%"></el-input>
        </el-form-item>
        <el-form-item style="margin-left: 30px" label="用户组">
          <el-select
            v-model="dialogForm.userGroup"
            style="width: 90%"
            placeholder="请选择用户组"
          >
            <el-option
              v-for="item in userGroups"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </template>
    </el-dialog>

    <div style="margin-top: 20px">
      <el-button
        type="primary"
        @click="handleBatchDelete"
        style="
          width: 100px;
          height: 40px;
          background-color: #e55443;
          border: none;
        "
        >批量删除</el-button
      >
      <el-button
        type="primary"
        @click="clearSelection"
        style="width: 100px; height: 40px"
        >取消选择</el-button
      >
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import * as XLSX from "xlsx";
import { format } from "date-fns";
import { ElMessage, ElMessageBox } from "element-plus";
const tableRef = ref(null); //复选框
import {
  getUserList,
  deleteUser,
  batchDeleteUser,
  editUser,
} from "@/api/index.js";

const selectedIds = ref([]); // 存储被勾选的行的 ID
const excelFileInput = ref(null); //导出
const pageSize = ref(7); // 每页显示的数据量(search)
const currentPage = ref(1); // 当前页码(search)
const total = ref(); // 总数据量
const dialogVisible = ref(false); // 模态框显示状态
const dialogForm = ref({ account: "", userGroup: "" }); //编辑模态框数据
const tableData = ref([]); // 表格数据
const userGroups = ref([
  { value: "超级管理员", label: "超级管理员" },
  { value: "普通管理员", label: "普通管理员" },
]);
// 定义列标题和对应的字段名
const columns = [
  { title: "ID", field: "id" },
  { title: "账号", field: "account" },
  { title: "用户组", field: "userGroup" },
  { title: "创建时间", field: "ctime" },
  { title: "头像", field: "imgUrl" },
];

//获取用户列表请求
const getUserListFn = async () => {
  const response = await getUserList({
    currentPage: currentPage.value,
    pageSize: pageSize.value,
  });
  console.log("🚀 ~ getUserListFn ~ response:", response);
  //处理日期格式
  response.data.forEach((item) => {
    item.ctime = formatDate(item.ctime);
  });
  // 给表格数据赋值
  tableData.value = response.data;
  //总页数
  total.value = response.total;
};

// 删除操作
const handleDelete = (row) => {
  ElMessageBox.confirm("确定要删除本用户吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      //调用删除请求
      const res = await deleteUser({
        id: row.id,
      });
      console.log("🚀 ~ .then ~ res:", res);
      if (res.code === 0) {
        getUserListFn();
        ElMessage({
          type: "success",
          message: "删除成功",
        });
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

// 清空复选框
const clearSelection = () => {
  if (tableRef.value) {
    tableRef.value.clearSelection();
  }
};

// 导出
const exportToExcel = () => {
  const data = [columns.map((col) => col.title)];
  // 将 tableData.value 中的每一项添加到二维数组中
  tableData.value.forEach((row) => {
    data.push(
      columns.map((col) => row[col.field] || "") // 使用 || '' 确保 undefined 值被转换为空字符串
    );
  });
  const ws = XLSX.utils.aoa_to_sheet(data);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
  XLSX.writeFile(wb, "tableData.xlsx");
};

// 导入
const importFromExcel = async (file) => {
  const reader = new FileReader();
  reader.onload = (e) => {
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, { type: "array" });
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];
    const json = XLSX.utils.sheet_to_json(worksheet);

    // 存储所有数据到 localStorage
    localStorage.setItem("importFromExcel", JSON.stringify(json));

    // 更新总数据量和每页数据量
    total.value = json.length;
    pageSize.value = 7; // 每页显示10条数据

    // 显示第一页数据
    handleCurrentChange(1);
  };
  reader.readAsArrayBuffer(file);
};
const handleExcelFileChange = (event) => {
  const files = event.target.files;
  if (files.length) {
    importFromExcel(files[0]);
  }
};

//导入
const handleIn = () => {
  excelFileInput.value.click(); // 触发文件选择
};

// 日期格式处理函数  ISO 8601 标准的日期时间
const formatDate = (dateString) => {
  return format(new Date(dateString), "yyyy-MM-dd HH:mm:ss");
};

// 分页器
const handleCurrentChange = (val) => {
  currentPage.value = val;

  // 检查是否有从 Excel 导入的数据
  const importedData = JSON.parse(localStorage.getItem("importFromExcel"));
  if (importedData) {
    // 计算当前页的数据范围
    const start = (val - 1) * pageSize.value;
    const end = val * pageSize.value;

    // 更新表格数据为当前页的数据
    tableData.value = importedData.slice(start, end);
  } else {
    // 如果没有导入数据，则请求获取用户列表
    getUserListFn();
  }
};

// 每页条目数改变时的处理函数
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1; // 重置为第一页
  getUserListFn();
};

// 批量删除处理函数
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage({
      type: "warning",
      message: "请先选择要删除的项",
    });
    return;
  }

  //删除提示
  ElMessageBox.confirm("确定要删除选中的项吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await batchDeleteUser({
          ids: selectedIds.value,
        });
        console.log("🚀 ~ .then ~ res:", res);
        if (res.code === 0) {
          ElMessage({
            type: "success",
            message: "批量删除成功",
          });
          // 重新获取数据
          getUserListFn();
        }
      } catch (error) {
        ElMessage({
          type: "error",
          message: "批量删除失败",
        });
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消批量删除",
      });
    });
};

// 处理行选择变化
const handleSelectionChange = (val) => {
  // 只保留被勾选的行的 ID
  const ids = val.map((row) => row.id);
  selectedIds.value = "[" + ids.join(",") + "]";
  console.log("111", selectedIds.value);
};

// 编辑操作
const handleEdit = (row) => {
  dialogForm.value = { ...row };
  dialogVisible.value = true;
};

//编辑模态框保存
const handleSave = async () => {
  try {
    const response = await editUser(dialogForm.value);
    if (response.code === 0) {
      ElMessage.success("编辑成功");
      dialogVisible.value = false;
      getUserListFn(); // 重新获取用户列表
    } else {
      ElMessage.error("编辑失败");
    }
  } catch (error) {
    console.error("编辑失败:", error);
    ElMessage.error("编辑异常");
  }
};

onMounted(() => {
  // 检查是否有导入的数据，并自动加载第一页数据
  const importedData = JSON.parse(localStorage.getItem("importFromExcel"));
  if (importedData) {
    total.value = importedData.length;
    pageSize.value = 10;
    tableData.value = importedData.slice(0, pageSize.value);
  } else {
    getUserListFn();
  }
});
</script>

<style scoped>
.flexbox {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
</style>
